<?php

class Reservations_BrowseSuccessView extends SrsReservationsBaseView
{
	public function executeHtml(AgaviRequestDataHolder $rd)
	{
		$this->setupHtml($rd);

		list ($year, $week, $day) = $this->extractDate($rd);

		$from = $this->getStartOfWeek($year, $week);
		$to   = strtotime('+1 week', $from);

		$this->setAttributes(array(
			'from' => $from,
			'to'   => $to,
			'year' => $year,
			'week' => $week,
			'day'  => $day,
   	));

		$this->setAttribute('reserveRoute', $this->user->hasCredential('reservations.add') ? 'reservation.add' : 'reservation.request');
  	$this->setAttribute('reservations', $this->getAttribute('hall')->getReservations($from, $to));
 	}

	private function extractDate(AgaviRequestDataHolder $rd)
	{
		$year = date('Y');
		$week = date('W');
		$day  = time();

		if ($rd->hasParameter('day'))
		{
			$day = $rd->getParameter('day');

			if (preg_match('/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/', $day))
			{
				$day = strtotime($day);

				$year = date('Y', $day);
				$week = date('W', $day);
			}
   	}
		elseif ($rd->hasParameter('year') && $rd->hasParameter('week'))
		{
			$year = (int)$rd->getParameter('year');
			$week = (int)$rd->getParameter('week');
		}

		return array($year, $week, $day);
	}

	private function getStartOfWeek($year, $week)
	{
		$jan1          = mktime(1, 1, 1, 1, 1, $year);
		$mondayOffset  = (11 - date('w', $jan1)) % 7 - 3;
		$desiredMonday = strtotime(($week - 1) . ' weeks ' . $mondayOffset . ' days', $jan1);

		return $desiredMonday;
	}
}